<?php
/**
钱包操作
 */

namespace App\Http\Controllers\Property;


use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Payment\Common\PayException;
use Payment\Client\Charge;
use Payment\Config;
use Payment\Client\Notify;
use App\Common\json;

class WalletController extends Controller
{
    //我的钱包
    public function mywallet(Request $request){
        if($request ->isMethod('post')){
            $userid    = $request ->input('userid');
            $data      = DB::table('user')
                ->select('usermoney','record_money','record_option','record_create_time')
                ->leftjoin('record','record.record_user','=','user.user_id')
                ->where('record_user',$userid)
                ->where('option',1)
                ->orderby('record_create_time','ASE')
                ->get();
            foreach ($data as $row) {
                if(empty($row ->usermoney)){
                    $key  = '0';
                }else{
                    $key = $row ->usermoney;
                }
                $tmpArray[$key]['service_type'] =$key;
                $tmpArray[$key]['service'][] =array('record_money'=>$row ->record_money,'record_option'=>$row ->record_option
                ,'time'=>$row ->record_create_time);
                $da = array_values($tmpArray);
            }
            if($data == true){
                return json::json('success', '获取收支明细数据成功', $da);
            }else{
                return json::json('failure','由于网络或者不正当原因获取收支明细数据失败',[]);
            }

        }
    }

    //添加银行卡

    public function addbank(Request $request)
    {
        $arr   = (object)array();
        if($request ->isMethod('post')){
            $userid       = $request ->input('userid');   //用户ID
            $bank_user    = $request ->input('name');     //用户姓名
            $bankID       = $request ->input('bankid');   //银行卡号
            $bankname     = $request ->input('bankname');
            $data         = DB::table('userbank')->where('bankID',$bankID)->first();
            if(empty($data ->bankID)){
                $insert  = DB::table('userbank') ->insert(['bank_userID'=>$userid,'bank_user'=>$bank_user,'bankID'=>$bankID,'bankname'=>$bankname]);
                if($insert == true){
                    return json::json('success', '恭喜您，银行数据添加成功', $arr);
                }else{
                    return json::json('failure','由于网络或者不正当原因银行数据添加失败',$arr);
                }
            }elseif ($data ->bankID == $bankID){
                return json::json('failure', '对不起，您添加的银行卡号已存在',$arr);
            }else{
                return true;
            }
        }
    }

    //展示银行
    public function showbank(Request $request)
    {
        if ($request->isMethod('post')) {
            $userid = $request->input('userid');
            $data = DB::table('userbank')->select('userbankID', 'bankID','bankname')->where('bank_userID', $userid)->get();
            if ($data == true) {
                return json::json('success', '恭喜您，银行数据获取成功', $data);
            } else {
                return json::json('failure', '由于网络或者不正当原因银行数据获取失败', []);
            }
        }
    }

    //金额
    public function showmonery(Request $request)
    {
        if ($request->isMethod('post')) {
            $userid = $request->input('userid');
            $data = DB::table('user')->select('usermoney')->where('user_id', $userid) ->get();
            foreach ($data as $value){
                if(empty($value ->usermoney)){
                    $money   = "0";
                }else{
                    $money  = $value ->usermoney;
                }
                $arr  = array(
                    'money' =>$money
                );
            }

            if ($data == true) {
                return json::json('success', '恭喜您，获取个人财产金额成功', $arr);
            } else {
                return json::json('failure', '由于网络或者不正当原因获取个人财产金额失败', []);
            }

        }
    }

    //提现
    public function withdraw(Request $request)
    {
        $arr = (object)array();
        if ($request->isMethod('post')) {
            $userid = $request->input('userid');
            $summoney = $request->input('summoney');
            $bankid = $request->input('bankid');
            $money = $request->input('money');
            $time  = date('Y-m-d H:i:s');
            if ($money <= 0) {
                return json::json('failure', '您提取的金额少于等零，提取失败', $arr);
            } elseif ($money > $summoney) {
                return json::json('failure', '您提取的金额大于总金额，提取失败', $arr);
            } else {
                $data = DB::table('record')->insert(array(
                    'record_user' => $userid, 'bank_id' => $bankid, 'record_money' => $money, 'record_option' => 2,'record_create_time'=>$time));
                if ($data == true) {
                    $value = $summoney - $money;
                    DB::table('user')->where('user_id', $userid)->update(['usermoney' => $value]);
                    return json::json('success', '恭喜您，提现请求发送成功', $arr);
                } else {
                    return json::json('failure', '由于网络或者不正当原因提现请求发送失败', $arr);
                }
            }
        }
    }

    //生成订单
    public function deltaorder(Request $request){
        if($request ->isMethod('post')){
            $Array          = (object)array();
            $order          = date('Ymdhis').rand(1000,9999);
            $user_id        = $request ->input('userid');  //用户ID
            $sum              = $request ->input('money');            //金额
            $order_status     = 0;
            $order_type       = $request ->input('type');
            $time             = date('Y-m-d H:i:s');
            $data             = DB::table('record')
                ->insert([
                    'recordorder'   =>$order,
                    'record_user'  =>$user_id,
                    'record_money' =>$sum,
                    'option'        =>$order_status,
                    'aplay_option'       =>$order_type,
                    'record_create_time'=>$time
                ]);
            if ($data == true) {
                return json::json('success', '订单生成成功',array('order'=>$order));
            } else {
                return json::json('failure', '订单生成失败', $Array);
            }
        }
    }

    //充值
    public function delta(Request $request,$type)
    {
        if ($request->isMethod('post')) {
            $order          = date('Ymdhis').rand(1000,9999);
            $user_id        = $request ->input('userid');  //用户ID
            $sum              = $request ->input('money');            //金额
            $order_status     = 0;
            $order_type       = $request ->input('type');
            $time             = date('Y-m-d H:i:s');
            DB::table('record')
                ->insert([
                    'recordorder'   =>$order,
                    'record_user'  =>$user_id,
                    'record_money' =>$sum,
                    'record_option' =>1,
                    'option'        =>$order_status,
                    'aplay_option'       =>$order_type,
                    'record_create_time'=>$time
                ]);
            switch ($type) {
                case "1":   //支付宝
                    $aliConfig = [
                        'use_sandbox' => false,// 是否使用沙盒模式
                        'partner' => '2088721065202522',
                        'app_id' => '2017052507339343',
                        'sign_type' => 'RSA2',// RSA  RSA2

                        // 可以填写文件路径，或者密钥字符串  当前字符串是 rsa2 的支付宝公钥(开放平台获取)
                        'ali_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmCrN9DnpHiQ7N8BJSCtKURvYJRKqbaCJwwhuXaayxgkvJ5TUyjJsJpOckSA1BJLmZRlz4HlwJrrFTIwS9pRxpPAeTFys6MwUTXgC5efmjT+3mGDrWsq6yjzfgtA0vr4N/zze7SnhVPI9aihtS55zt+twOpp3qwTkcA+a8P2+B9Lq/jFqDeM9qLTS9ZzGSrdO58G5t/hjNmmQycP7rhZCWTp4NK4gbRWjqw2g128coZJJlWc/M71E6jEQ5suw6dbC2596/TKOikYyzD52Et8PVp7axo/LG2zIr3fT7/5FIEfDi4pd3/NW8IvsAEipbuEuMNUJxUXwgDZqmjTvfK77RwIDAQAB',

                        // 可以填写文件路径，或者密钥字符串  我的沙箱模式，rsa与rsa2的私钥相同，为了方便测试
                        'rsa_private_key' => 'MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCk/SWK+rivKCiRrMkFYG2rR0YicVDzrpgGdYA9KKpUD8t94K1m4oCVT1R9eu53Jq5YmNzFCqFQooMcA0OvB4iVzpJMmSVUGQolFL5VnEkxhLk2zHTm35snCQYjrqiXjl2wwM7GvAzvBivRgbPoTUCJ+nbW0ybGM+85nSlbgJSNGcAgo8Pmr/cGgmbwQcmsNVtipgpraL2blI3qhLeYH10G0oz9kCM1xU5FF4ZgDVetbKDfzI0t3TEvVu9r/lbUp08XWgEp4c7defxRca69CZBWJrftEMpPDDLQws+zh6uVjWxzxEdMNypvIQEogF++zpFiEvXEYain/hugtoJ7I/yLAgMBAAECggEADyhmu5b/QrBY0dFjAohyaur4aY+plUm0E9vVtUi4JVLyKhVrOOmUUKNiKskRgYbfO6qHld69JVBY5UjzffAeP00kKb9kK47FXNTEC8949gCwl3U/RDrE4Vg15S9Vs97TgrqkBKQgOBGEExJseeonBMYrBt+NT2ZUEyH6O7rbav8NHXb00L70fNnFxc7LxSEyEAgPXx/5qDJW3lgJYxQJRd5PSk7p0jgc6uiTLdjQDKIgoyNcX4rgCH3XVrSI7LVFjL+j3y2ra/ZQkCCfi4xTlabOkTfblyOZH+QtomkmdfidZTLfJ3LZqVlstgLeMgYMQj/55sX5/iZfas4+TMlZ2QKBgQD7RDbMJDnUQhViTU4fm8bVEDlNPJzrmrNRUTrAXNKVLsHFCfiDFZvzIykfZ7RUvaqhB4QMu8eU62eGPKcYO5ECitZSzBGd5vbjeXIT4EY8FKMX0RyTQz1GaGM/hWKNhPtRtM5vVw3doU5jfldGphIwLV8ZznFN+4XY8+UUdJMiZQKBgQCoGNcqXld4cvNZGEbjw5p64AEGLZdHDDt08ssE1RyM6xa6EH7qyAZbpFAE/bSOi9VVYSX0m8irz7JcyfvN6lSTo0u+Z0WOuv+RJoVhSTBhvClZyJnUiErk8j7t/fs+KRmtpy52XZXCJRDRIqGrfX4qAUnbFBbXwYAlCFS4bj08LwKBgEox4lx1df4PZXEZkrASt6vClqkP9OY9UCX67nZO8n/Kxr0ALLnIb7xj7YiwfrdnKjNSnNOFv3Fh8bfZwR2OuUse5Bqe17TgtpaFDgKAfzzOezpVLTLu7/EScfwXzvorAmsmEK8f7aA8OYF3lR3ve/9t5l8gbqSwWN2vZz2bDrdhAoGAR54dvg1n0weWqnTvbwbdgFCD3y/5benGQzNWT/7EJT3b9vYkPL9wBgdhmF7HWJw3DiNP2oGs45af9WyQ/dBCrIw8Lykst3zwedUhqqtWE63pKDmRYL2YuyaCrT8yle9I43WBFCkXLxo/qfrJSpky8Y6O+un6OX5VrHF6NwGw0T0CgYAllYiZrBonvLCx33uEshjgd9Kt8gwHY56DhF4NPqZaozCMId86G+DghglB6H7MjjgYY9zkRZ+W06stKOZXQaKEUOc2jSJmfoZI2LNBGcOjiiF7VrvR3Xd6FweITW2m+VklPh6ndmAJEsc+izlJHKJUReT2kE/k6P7c9VmISGixQA==',


                        // 与业务相关参数
                        'notify_url' => 'http://www.mukitech.com/wuye/app/public/property/PaySuccess',
                        //'return_url'                => 'http://www.mukitech.com/wuye/app/public/property/PaySuccess',

                        'return_raw' => true,// 在处理回调时，是否直接返回原始数据，默认为 true
                    ];
                    $payData = [
                        'body' => 'ali qr pay',
                        'subject' => "支付宝充值",
                        'order_no' => $order,
                        'timeout_express' => time() + 600,// 表示必须 600s 内付款
                        'amount' => '0.01',// 单位为元 ,最小为0.01
                        'return_param' => '123123',
                        'client_ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1',// 客户地址
                        'goods_type' => '1',
                        'store_id' => '',
                    ];
                    try {
                        $str = Charge::run(Config::ALI_CHANNEL_APP, $aliConfig, $payData);
                    } catch (PayException $e) {
                        echo $e->errorMessage();
                        exit;
                    }
                    $dd = array('value' => $str);
                    return json::json('success', '获取支付数据成功', $dd);
                    break;
                case "2":
                    $wxConfig = [
                        'use_sandbox'       => false,// 是否使用 微信支付仿真测试系统
                        'app_id'            => 'wx58f7d9a1d1591311',  // 公众账号ID
                        'mch_id'            => '1487628602',// 商户id
                        'md5_key'           => 'raS7PylXxB7ENHL7loeepRZJryaCds2c',// md5 秘钥
                        //'APPSECRET'         => 'd6bd2356c104deb1e97d6d12b9a5417f',
                        'app_cert_pem'      => dirname(__FILE__) . DIRECTORY_SEPARATOR . 'wx' . DIRECTORY_SEPARATOR .  'pem' . DIRECTORY_SEPARATOR . 'weixin_app_cert.pem',
                        'app_key_pem'       => dirname(__FILE__) . DIRECTORY_SEPARATOR . 'wx' . DIRECTORY_SEPARATOR .  'pem' . DIRECTORY_SEPARATOR . 'weixin_app_key.pem',
                        'sign_type'         => 'MD5',// MD5  HMAC-SHA256
                        'limit_pay'         => [
                            //'no_credit',
                        ],// 指定不能使用信用卡支付   不传入，则均可使用
                        'fee_type'          => 'CNY',// 货币类型  当前仅支持该字段

                        'notify_url'        => 'http://www.mukitech.com/wuye/app/public/property/wxsuccess',

                        'redirect_url'      => '',// 如果是h5支付，可以设置该值，返回到指定页面

                        'return_raw'        => false,// 在处理回调时，是否直接返回原始数据，默认为true
                    ];

                    $payData = [
                        'body'    => 'test body',
                        'subject'    => '微信充值',
                        'order_no'    => $order,
                        'timeout_express' => time() + 600,// 表示必须 600s 内付款
                        'amount'    => '0.01',// 微信沙箱模式，需要金额固定为3.01
                        'return_param' => '123',
                        'client_ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1',// 客户地址
                    ];

                    try {
                        $ret = Charge::run(Config::WX_CHANNEL_APP, $wxConfig, $payData);
                    } catch (PayException $e) {
                        echo $e->errorMessage();
                        exit;
                    }
                  //  $dd = array('value' => $ret);
                    return json::json('success', '获取支付数据成功', $ret);
                    break;
                default:
                    break;
            }
        }
    }

    public function wxsuccess(Request $request)
    {
        if ($request->isMethod('post')) {
          //  $callback = new TestNotify();
            $wxConfig = [
                'use_sandbox' => false,// 是否使用 微信支付仿真测试系统
                'app_id' => 'wx58f7d9a1d1591311',  // 公众账号ID
                'mch_id' => '1487628602',// 商户id
                'md5_key' => 'raS7PylXxB7ENHL7loeepRZJryaCds2c',// md5 秘钥
                //'APPSECRET'         => 'd6bd2356c104deb1e97d6d12b9a5417f',
                'app_cert_pem' => dirname(__FILE__) . DIRECTORY_SEPARATOR . 'wx' . DIRECTORY_SEPARATOR . 'pem' . DIRECTORY_SEPARATOR . 'weixin_app_cert.pem',
                'app_key_pem' => dirname(__FILE__) . DIRECTORY_SEPARATOR . 'wx' . DIRECTORY_SEPARATOR . 'pem' . DIRECTORY_SEPARATOR . 'weixin_app_key.pem',
                'sign_type' => 'MD5',// MD5  HMAC-SHA256
                'limit_pay' => [
                    //'no_credit',
                ],// 指定不能使用信用卡支付   不传入，则均可使用
                'fee_type' => 'CNY',// 货币类型  当前仅支持该字段

                'notify_url' => 'http://www.mukitech.com/wuye/app/public/property/wxsuccess',

                'redirect_url' => '',// 如果是h5支付，可以设置该值，返回到指定页面

                'return_raw' => false,// 在处理回调时，是否直接返回原始数据，默认为true
            ];
            $type = 'wx_charge';// ali_charge wx_charge  cmb_charge
            try {
                // 获取第三方的原始数据，未进行签名检查，根据自己需要决定是否需要该步骤
                $retData = Notify::getNotifyData($type, $wxConfig);
                Log::info($retData);
                // $ret = Notify::run($type, $aliConfig, $callback);// 处理回调，内部进行了签名检查
                // $dd = $retData['trade_status'];
                if($retData) {
                    if ($retData['result_code'] == 'SUCCESS') {
                        DB::table('record')->where('recordorder', $retData['out_trade_no'])->update(['option' => 1]);
                        $select = DB::table('record')->where('recordorder', $retData['out_trade_no'])->first();
                        $data = DB::table('user')->where('user_id', $select->record_user)->first();
                        $money = $data->usermoney + $select->record_money;
                        DB::table('user')->where('user_id', $select->record_user)->update(['usermoney' => $money]);

                    }
                    echo "success";		//请不要修改或删除
                }else{
                    echo "fail";	//请不要修改或删除
                }


            } catch (PayException $e) {
                 echo $e->errorMessage();
                exit;
            }
        }
    }

    public function delbank(Request $request){
        if($request ->isMethod('post')){
            $arr   = (object)array();
            $bankid    = $request ->input('bankid');
            $data      = DB::table('userbank') ->where('userbankID',$bankid)->delete();
            if ($data == true) {
                return json::json('success', '银行卡删除成功',$arr);
            } else {
                return json::json('failure', '银行卡删除失败', $arr);
            }
        }
    }

    public function updatebank(Request $request){
        if($request ->isMethod('post')){
            $arr   = (object)array();
            $id    = $request ->input('id');
            $bankid = $request ->input('bankid');
            $bankuser = $request ->input('bankuser');
            $data     = DB::table('userbank')->where('userbankID',$id)
                      ->update(['bankID'=>$bankid,'bank_user'=>$bankuser]);
            if ($data == true) {
                return json::json('success', '银行卡修改成功',$arr);
            } else {
                return json::json('failure', '银行卡修改失败', $arr);
            }

        }
    }
}